package my.yuan.fkzapp.response;

import my.yuan.fkzcommon.domain.code.ResponseCode;
import my.yuan.fkzcommon.exception.GenericException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

/**
 * @author qy
 * @description GlobalExceptionHandler
 * @date 2021-10-01
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public CommonResult<?> handle(RuntimeException e) {
        return CommonResult.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = GenericException.class)
    public CommonResult<?> handle(GenericException e) {
        return e.getMessage() == null ? CommonResult.fail(e.getCode()) : CommonResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 控制层参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResult<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMsg = bindingResult.getFieldErrors().stream()
                .map(t -> t.getField() + ": " + t.getDefaultMessage())
                .collect(Collectors.joining(", "));
        return CommonResult.fail(ResponseCode.INPUT_PARAM_ERR, errorMsg);
    }

}
